'use strict';

import React from 'react';
import { connect } from 'react-redux';
import { Link} from 'react-router';
import * as actions from '../../actions/ring_zhekou_list';
import * as edit_items_actions from '../../actions/zhekou1_edit_items';
import { Button,Icon,Dialog,Pagination,Search,Form,Loading,Menu,Tab,Input} from 'qnui';
import Radio,{ Group as RadioGroup } from 'qnui/lib/radio';
import { Row, Col } from 'qnui/lib/grid';
import Breadcrumb from 'qnui/lib/breadcrumb'
import Step, { Item as StepItem } from 'qnui/lib/step';
import DatePicker, { RangePicker } from 'qnui/lib/date-picker';
import ZhekouTags from 'components/zhekou-tags/index';
import './index.scss';

class RingZhekouList extends React.Component {
    constructor(props) {
        super(props);
		this.dispatch = this.props.dispatch;
        this.state = {
			refreshDialog:false,
			refreshContent:"",
			currentPage:1,
			pageSize:10,
			editActive:false,
			overlayVisible:false,
			tagName:false,
			active:false,
			start_time:false,
			end_time:false,
			activeType:"limit",
			choseDialog:false,
			choseTask:false,
			tag_id:this.props.location.state.tag_id
        };
		this.dispatch(
			edit_items_actions.clearList()
		);
		this.dispatch(
			actions.getList({
				tag_id:this.state.tag_id,
				active_type:this.state.activeType,
				page:1,
				page_size:this.state.pageSize
			})
		);
    }
	onClose(){
		this.dispatch(actions.closeDialog());
	}
	onRefreshClose(){
		this.setState({"refreshDialog":false});
	}
	handleCheckStatus(){
		return;
	}
	handlePageChange(page){
		this.setState({"currentPage":page});
		this.dispatch(
			actions.getList({
				tag_id:this.state.tag_id,
				active_type:this.state.activeType,
				page:page,
				page_size:this.state.pageSize
			})
		);
	}
	handlePageSizeChange(size){
		this.setState({"currentPage":1,"pageSize":size});
		this.dispatch(
			actions.getList({
				tag_id:this.state.tag_id,
				active_type:this.state.activeType,
				page:1,
				page_size:size
			})
		);
	}
	handleEditActive(active){
		this.setState({
			editActive:true,
			tagName:active.name,
			start_time:false,
			end_time:false,
			overlayVisible:false,
			is_decrease_money:false,
			decrease_amount:"",
			is_discount:false,
			discount_rate:"",
			active
		});
	}
	onEditOk(){
		if(this.loginRefresh()){//检测超时
			return;
		}
		if(this.state.tagName!=this.state.active.name || this.state.start_time || this.state.end_time || this.state.is_decrease_money || this.state.is_discount){
			// 有任何一样重设则提交请求，否则关闭对话框
			const allshop={};
			if(this.state.activeType=="allshop"){
					const amountEx = new RegExp(/^\d+(\.([1-9]|\d[1-9]))?$/);
					if(this.state.is_decrease_money && !amountEx.test(this.state.decrease_amount)){
						 Dialog.alert({content: '支持2位小数，末尾不为0'});
						 return;
					}
					const rateEx = new RegExp(/^\d{1}(\.([1-9]|\d[1-9]))?$/);
					if(this.state.is_discount && !rateEx.test(this.state.discount_rate)){
						 Dialog.alert({content: '请输入0.01-9.99'});
						 return;
					}
					allshop.is_decrease_money=this.state.is_decrease_money,
					allshop.decrease_amount=this.state.decrease_amount,
					allshop.is_discount=this.state.is_discount,
					allshop.discount_rate=this.state.discount_rate
			}
			this.dispatch(
				actions.editActive({
					...allshop,
					activity_id : this.state.active.activity_id,
					name : this.state.tagName?this.state.tagName:this.state.active.name,
					description : this.state.active.description?this.state.active.description:"人群标签为"+this.state.tag_id+"的折扣",
					start_time : this.state.start_time? this.state.start_time:this.state.active.start_time,
					end_time : this.state.end_time? this.state.end_time:this.state.active.end_time,
					tag_id : this.state.tag_id,
					
					
				},this.state.activeType)
			);
		}else{
			this.setState({overlayVisible:false,editActive:false});
		}
	}
	onEditCancel(){
		this.setState({editActive:false});
	}
	setTag(tagName){
		this.setState({tagName,overlayVisible:false});
	}
	searchResult(hasTag,isPrefect){
		this.setState({"hasTag":hasTag,"isPrefect":isPrefect});
	}
	handleShowSearchTag(){
		this.setState({overlayVisible:true});
	}
	setStartTime(start_time){
		this.setState({start_time});
	}
	setEndTime(end_time){
		this.setState({end_time});
	}
	removeActive(activity_id){
		this.dispatch(
			actions.removeActive(activity_id,this.state.activeType,this.state.tag_id)
		);
	}
	handleChangeActiveType(key){
		this.setState({activeType:key});
		this.dispatch(
			actions.getList({
				tag_id:this.state.tag_id,
				active_type:key,
				page:1,
				page_size:this.state.pageSize
			})
		);
	}
	handleGo(type){
		switch(type){
			case "normal":
				this.props.history.pushState(this.props.location.state, '/ring_tags_step2?act_type=item');
				break;
			case "limit":
				this.props.history.pushState({...this.props.location.state}, '/ring_tags_step2?act_type=limit');
				break;
		}
		this.setState({choseDialog:false});
	}
	showChoseDialog(){
		this.setState({choseDialog:true});
	}
	closeChoseDialog(){
		this.setState({choseDialog:false});
	}
	amountChange(val,callback){
		this.setState({is_decrease_money:true,is_discount:false,decrease_amount:val});
	}
	rateChange(val,callback){
		this.setState({is_discount:true,is_decrease_money:false,discount_rate:val});
	}
	loginRefresh(){
		
		const ts = Date.parse(new Date())/1000;
		if(parseInt(window.info.timestemp)+1700 < ts){
			// 操作授权超过半小时，请重新授权			
			// window.parent.closeRefreshDialog();  iframe页面调用该关闭方式
			let _self = this;
			window.closeRefreshDialog = (info)=>{
				window.info = info; //刷新已授权的信息
				_self.setState({"refreshDialog":false});
			}
			this.setState({"refreshDialog":true,"refreshContent":{"title":"敏感操作授权超时","msg":"请授权并在30分钟以内完成创建折扣。","content":<iframe name="showLogin" id="showLogin" style={{border:"none",height:"360px",width:"100%"}}  scrolling="no" src={"https://oauth.taobao.com/authorize?client_id=21127968&redirect_uri=http%3A%2F%2Fllxl.hz.taeapp.com%2F?a=refresh&response_type=code&state=llxl.hz.taeapp.com.21127968&view=web&ts="+ts} />}});
			return true;
		}
		return false
	}
  render() {
	const loginBtn = this.props.ring_zhekou_list.loginError?
				<a href="https://oauth.taobao.com/authorize?response_type=code&client_id=21127968&redirect_uri=http://llxl.hz.taeapp.com/?state=ring_zhekou_list&view=web"><Button size="large" type="primary"><span>请重新登陆</span></Button></a>
			 :"";
	const footer = this.props.ring_zhekou_list.loginError?<div>{loginBtn}</div>:"";
	const creatingTitle = this.props.ring_zhekou_list.loading?"正在读取。。。":"错误信息";
	const creatingMsg = this.props.ring_zhekou_list.loading?<Loading />:this.props.ring_zhekou_list.message;
	const creatingDialog = this.props.ring_zhekou_list.loading?true:this.props.ring_zhekou_list.error;
	const data = this.props.ring_zhekou_list.data;
	const activitys = data?data.activity_list.common_item_activity:[];
	const total = data?parseInt(data.total_count):0;
	const noneMsg = total?"":<Row justify="center">没有任何折扣</Row>;
	
	const tags = <ZhekouTags 
					setTag={this.setTag.bind(this)}	
					search={this.state.search}
					searchResult={this.searchResult.bind(this)}
					curTag={this.state.tagName}
				/>
	const tabBarExtra = 
		<div>
				<Col span="12">
					<Button onClick={this.showChoseDialog.bind(this)}
						size="large" 
						type="normal"  
						style={{padding:"0 8px"}} 
						shape="warning">
							<Icon type="add" />
								创建折扣
							</Button>
				</Col>
		</div>;
	const setDes = this.state.activeType=="allshop"?
					<Row style={{paddingLeft:"60px"}}>
						<Form.Item style={{width:"132px"}}>
							<Input 
								style={{width:"122px"}}
								size="large" 
								addonBefore="打" 
								state={this.state.is_discount=="true"?"success":""}
								value={this.state.is_discount?this.state.discount_rate:""}
								onChange={this.rateChange.bind(this)}
								addonAfter="折" 
							/>
						</Form.Item>
						<Form.Item style={{width:"132px"}}>
							<Input 
								style={{width:"122px"}}
								size="large" 
								addonBefore="减" 
								state={this.state.is_decrease_money=="true"?"success":""}
								value={this.state.is_decrease_money?this.state.decrease_amount:""}
								onChange={this.amountChange.bind(this)}
								addonAfter="元" 
							/>
						</Form.Item>
					</Row>
					:"";
	return (
        <div className="page1-page">
			<Row style={{background:"#F6F6F6",margin:"3px 0",height:"43px"}} justify="start">
			<Col span="8" align="center">
			<Breadcrumb maxNode={5}>
				  <Breadcrumb.Item>打折活动</Breadcrumb.Item>
				  <Breadcrumb.Item>限时折扣</Breadcrumb.Item>
				  <Breadcrumb.Item>活动列表</Breadcrumb.Item>
			  </Breadcrumb>
			</Col>
		  </Row>
		    <Dialog
					visible = {this.state.refreshDialog}
                    onOk = {this.onRefreshClose.bind(this)}
                    onCancel = {this.onRefreshClose.bind(this)}
                    onClose = {this.onRefreshClose.bind(this)} 
					title = {this.state.refreshContent.title}
					style={{width:"445px",height:"360px"}}
					footer = {""}
					>
					<Row justify="center">
						{this.state.refreshContent.msg}
					</Row>
					<Row justify="center">
						{this.state.refreshContent.content}
					</Row>
            </Dialog>
			<Dialog style={{width:"300px"}} 
					visible = {creatingDialog}
                    onOk = {this.onClose.bind(this)}
                    onCancel = {this.onClose.bind(this)}
                    onClose = {this.onClose.bind(this)} 
					title = {creatingTitle}
					footer = {footer}
					>
					<Row justify="center">
						<h3>{creatingMsg}</h3>
					</Row>
            </Dialog>
			<Dialog style={{width:"680px"}} 
					visible = {this.state.editActive}
                    onOk = {this.onEditOk.bind(this)}
                    onCancel = {this.onEditCancel.bind(this)}
                    onClose = {this.onEditCancel.bind(this)} 
					title = "修改折扣"
					>
					<Row justify="center">
						<Col span="21">
							<Search 
								size="large"
								 placeholder="选择标签"
								 type="normal"
								 combox={tags}
								 overlayVisible={this.state.overlayVisible}
								 value={this.state.tagName}
								 hasIcon={false}
								 searchText="　"
								 autoWidth
								 className="tagSearch"
								 onSearch={()=>{}}
								 onClick={this.handleShowSearchTag.bind(this)}
							/>
						</Col>
					</Row>
					<Row justify="center">
					    <Form labelAlign="inset" span="21">
							<Col span="12">
								<Form.Item label="开始"><DatePicker size="large" defaultValue={Date.parse(this.state.active.start_time)} onChange={this.setStartTime.bind(this)} placeholder="选择开始时间" showTime/></Form.Item>
							</Col>
							<Col span="12">
								<Form.Item label="结束"><DatePicker size="large" defaultValue={Date.parse(this.state.active.end_time)} onChange={this.setEndTime.bind(this)} placeholder="选择结束时间"showTime/></Form.Item>
							</Col>
						</Form>
					</Row>
					{setDes}
            </Dialog>
			<Dialog
				visible={this.state.choseDialog}
				title="请选择创建类型："
				onClose={this.closeChoseDialog.bind(this)}
				footer={false}
				>
				<Row>
						<Col span="12">
						<Button onClick={this.handleGo.bind(this,"normal")}>普通折扣</Button>
						</Col>
						<Col span="12" offset="2">
						<Button offset="2" onClick={this.handleGo.bind(this,"limit")}>限购折扣</Button>
						</Col>
				</Row>
			</Dialog>
		<Tab type="wrapped" onChange={this.handleChangeActiveType.bind(this)} tabBarExtraContent={tabBarExtra} contentStyle={{borderBottom:"none",height:"0",padding:"0",minHeight:"0",marginTop:"-1px",top:"0"}}>
			<Tab.TabPane tab="限购折扣" key="limit" />
			<Tab.TabPane tab="普通折扣" key="item" />
			{/*<Tab.TabPane tab="全店折扣" key="allshop" />全店折扣已下线*/}
        </Tab>
		<div style={{padding:"5px",borderLeft:"1px solid #e6e6e6",borderBottom:"1px solid #e6e6e6",borderRight:"1px solid #e6e6e6"}}>
		<Row align="center" style={{marginTop:0,paddingTop:"5px"}} className="list">
					<Col>
						活动标签
					</Col>
					<Col>
						描述
					</Col>
					<Col>
						开始时间
					</Col>
					<Col>
						结束时间
					</Col>
					<Col>
					操作
					</Col>
					<Col fixedSpan="5">
					管理
					</Col>
				</Row>
				{noneMsg}
				{activitys.map((active,key)=>{
					let time = new Date();
					let start_time = new Date(active.start_time);
					let end_time = new Date(active.end_time);
					let is_waitting = time.getTime()<start_time.getTime();
					let is_end = time.getTime()>end_time.getTime();
					let statu = is_waitting?"未开始":(is_end?"已结束":"进行中");
					let color = is_waitting?"#3089DC":(is_end?"#C7C7C7":"#1BB11B");
					const showItemBtn = this.state.activeType=="allshop"?"":
							<Col fixedSpan="5">
								<Link to={'/ring_zhekou_edit_items?activity_id='+active.activity_id+"&act_type="+this.state.activeType+"&is_edit=1"}><Button shape="ghost" >查看商品</Button></Link>
							</Col>;
					const menu = <Menu>
									<Menu.Item key={active.activity_id} onClick={this.removeActive.bind(this)}>删除</Menu.Item>
								</Menu>
					return(
					<Row key={key} align="center" className="list" style={{color:color}}>
						<Col>
							{active.name}
						</Col>
						<Col>
							{active.description}
						</Col>
						<Col>
							{active.start_time}
						</Col>
						<Col>
							{active.end_time}
						</Col>
						<Col fixedSpan="4">
							{statu}
						</Col>
						<Col fixedSpan="5">
							<Button.Split size="small" type="secondary" menu={menu} onClick={this.handleEditActive.bind(this,active)}>修改</Button.Split>
						</Col>
						{showItemBtn}
					</Row>
					)
				})}
				<Row justify="end">
					<Col span="12">
						 <Pagination current={this.state.currentPage} total={total} pageSize={this.state.pageSize} pageSizeList={[10,20,30]} pageSizeSelector="dropdown" type="simple" onChange={this.handlePageChange.bind(this)} onPageSizeChange={this.handlePageSizeChange.bind(this)} />
					</Col>
				</Row>
			</div>
        </div>
    );
  }
}


export default connect((state)=> {
  return {
    ring_zhekou_list: state.ring_zhekou_list
  };
})(RingZhekouList);
